package cn.com.bob.messageboard.controller;
import cn.com.bob.messageboard.domain.JsonResult;
import cn.com.bob.messageboard.domain.User;
import cn.com.bob.messageboard.service.UserService;
import cn.com.bob.messageboard.utils.JwtConstant;
import cn.com.bob.messageboard.utils.JwtTokenUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static cn.com.bob.messageboard.controller.BaseController.OK;

/**
 * @Author Bob
 * @Version：1.0
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;



    /**
     * 注册功能
     * @param :
     * @return ResponseEntity<Void>
     */
    @PostMapping("/register")
    @ResponseBody
    public JsonResult<Void> register(String username,String password,String email,String emailCode){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setEmailCode(emailCode);

        System.out.println(username);
        System.out.println(password);
        System.out.println(email);
        System.out.println(emailCode);
        userService.register(user);
        return new JsonResult<>(OK);
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 登录
     * @param
     * @return JsonResult<User>
     */
    @PostMapping("/login")
    @ResponseBody
    public JsonResult<String> login(String username, String password, HttpServletResponse response){
        User user = userService.login(username, password);
        //创建jwt
        Map<String, Object> map = new HashMap<>();
        map.put(JwtConstant.USER_INFO_USERNAME,user.getUsername());
        map.put(JwtConstant.USER_INFO_ID,user.getUserId());
        map.put(JwtConstant.JWT_CREATE_TIME,new Date());
        String jwt = JwtTokenUtil.createToken(map);
        redisTemplate.opsForValue().set(user.getUserId().toString(),jwt);

        Cookie cookie = new Cookie("token",jwt);
        cookie.setMaxAge(60*60*24);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new JsonResult<>(OK,user.getUsername());
    }





}
